package com.electric.qrapp.utils.function

import android.Manifest
import androidx.fragment.app.FragmentActivity
import com.electric.qrapp.utils.system.showToast
import com.huawei.hms.hmsscankit.ScanUtil
import com.huawei.hms.ml.scan.HmsScan
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions
import com.permissionx.guolindev.PermissionX

/**
 *@author:Fanatic
 *@date:2021/8/12 21:45
 *@des: 扫码工具类
 */
object ScanUtils {

    fun startScan(activity: FragmentActivity, requestCode: Int) {
        PermissionX.init(activity)
            .permissions(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
            .onExplainRequestReason { scope, deniedList ->
                scope.showRequestReasonDialog(
                    deniedList,
                    "您必须先同意此权限才能使用扫码服务",
                    "好的",
                    "取消"

                )

            }.request { allGranted, _, _ ->
                if (allGranted) {
                    scan(activity,requestCode)
                } else {
                    showToast(msg = "权限被拒绝，无法启动扫码服务")
                }
            }
    }

    private fun scan(activity: FragmentActivity,requestCode: Int){
        ScanUtil.startScan(
            activity,
            requestCode,
            HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.ALL_SCAN_TYPE).create()
        )
    }

}